import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getDepartmentList, addDepartment, updateDepartment, deleteDepartment } from '@/api/department'
import type { DepartmentItem, AddDepartmentParams, UpdateDepartmentParams } from '@/api/types/department'
import { ElMessage } from 'element-plus'

export const useDepartmentStore = defineStore('department', () => {
  const departmentList = ref<DepartmentItem[]>([])
  const loading = ref(false)

  // 获取部门列表
  const fetchDepartmentList = async () => {
    loading.value = true
    
    try {
      const response = await getDepartmentList()
      if (response.code === '200') {
        // 创建固定的公司数据
        const companyData: DepartmentItem = {
          id: 0,
          selfid: 0,
          dept_name: '名创优品香港分公司',
          pid: -1,
          childs: response.data.info_list
        }
        departmentList.value = [companyData]
      } else {
        ElMessage.error(response.msg || '获取部门列表失败')
      }
    } catch (error) {
      console.error('获取部门列表失败:', error)
      ElMessage.error('获取部门列表失败')
    } finally {
      loading.value = false
    }
  }

  // 新增部门
  const addDepartmentAction = async (data: AddDepartmentParams) => {
    try {
      const response = await addDepartment(data)
      if (response.code === '200') {
        ElMessage.success(response.msg || '新增成功')
        await fetchDepartmentList()
        return true
      } else {
        ElMessage.error(response.msg || '新增失败')
        return false
      }
    } catch (error) {
      console.error('新增部门失败:', error)
      ElMessage.error('新增部门失败')
      return false
    }
  }

  // 编辑部门
  const updateDepartmentAction = async (data: UpdateDepartmentParams) => {
    try {
      const response = await updateDepartment(data)
      if (response.code === '200') {
        ElMessage.success(response.msg || '修改成功')
        await fetchDepartmentList()
        return true
      } else {
        ElMessage.error(response.msg || '修改失败')
        return false
      }
    } catch (error) {
      console.error('编辑部门失败:', error)
      ElMessage.error('编辑部门失败')
      return false
    }
  }

  // 删除部门
  const deleteDepartmentAction = async (selfid: number) => {
    try {
      const response = await deleteDepartment({ selfid })
      if (response.code === '200') {
        ElMessage.success(response.msg || '删除成功')
        await fetchDepartmentList()
        return true
      } else {
        ElMessage.error(response.msg || '删除失败')
        return false
      }
    } catch (error) {
      console.error('删除部门失败:', error)
      ElMessage.error('删除部门失败')
      return false
    }
  }

  return {
    departmentList,
    loading,
    fetchDepartmentList,
    addDepartment: addDepartmentAction,
    updateDepartment: updateDepartmentAction,
    deleteDepartment: deleteDepartmentAction
  }
}) 